<template>
  <div>
    <Row>
      <Col :span="18">
        <DatePicker
          type="daterange"
          v-model="params.date"
          clearable
          :transfer="true"
          @on-change="askData"
          placeholder="日期选择"
        />
        <Select
          v-model="params.project_id"
          v-width="150"
          placeholder="请选择项目"
          clearable
          :transfer="true"
          @on-change="askData"
          class="ivu-ml-8"
        >
          <Option
            v-for="item in projectList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
        <Select
          v-model="params.channel_id"
          v-width="150"
          placeholder="请选择渠道"
          clearable
          multiple
          :transfer="true"
          @on-change="askData"
          class="ivu-ml-8"
        >
          <Option
            v-for="item in channelList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </Col>
      <Col :span="6" class="ivu-text-right">
        <Button
          type="warning"
          :loading="synLoading"
          v-hasC="{
            name: 'v1-marketing-dingtalk-syn-dingtalk-money-record',
            flag: 'v1/marketing/dingtalk/syn-dingtalk-money-record',
          }"
          @click="synchronous"
          >钉钉数据同步</Button
        >
        <Button
          type="primary"
          class="ivu-ml-8"
          v-hasC="{
            name: 'v1-marketing-bill-recharge-update-bill-recharge',
            flag: 'v1/marketing/bill-recharge/update-bill-recharge',
          }"
          @click="handleAdd"
          >新增</Button
        >
      </Col>
    </Row>
    <Table
      :columns="columns"
      :data="data"
      :loading="loading"
      class="ivu-mt-16"
      :max-height="560"
      show-summary
      :summary-method="handleSummary"
    >
      <template slot="channel_name" slot-scope="{ row }"
        ><span :class="row.channel_id == 0 ? 'nochannel' : ''"
          >{{ row.channel_name }} /{{ row.subdivided_channels_name }}</span
        ></template
      >
      <template slot="type_name" slot-scope="{ row }">
        <Tooltip
          :content="row.business_id"
          v-if="row.type == 2"
          placement="top"
        >
          {{ row.type_name }}
        </Tooltip>
        <span v-else>{{ row.type_name }}</span>
      </template>
      <template slot="action" slot-scope="{ row }">
        <span v-if="row.type == 2 || !row.edit_status">
          <a
            disabled
            v-hasC="{
              name: 'v1-marketing-bill-recharge-update-bill-recharge2',
              flag: 'v1/marketing/bill-recharge/update-bill-recharge',
            }"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-marketing-bill-recharge-update-bill-recharge2',
              flag: 'v1/marketing/bill-recharge/update-bill-recharge',
            }"
          />
          <a
            disabled
            v-hasC="{
              name: 'v1-marketing-bill-recharge-delete-bill-recharge',
              flag: 'v1/marketing/bill-recharge/delete-bill-recharge',
            }"
            >删除</a
          >
        </span>
        <span v-else>
          <a
            @click="handleEdit(row)"
            v-hasC="{
              name: 'v1-marketing-bill-recharge-update-bill-recharge2',
              flag: 'v1/marketing/bill-recharge/update-bill-recharge',
            }"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-marketing-bill-recharge-update-bill-recharge2',
              flag: 'v1/marketing/bill-recharge/update-bill-recharge',
            }"
          />
          <a
            @click="handleDel(row)"
            class="del"
            v-hasC="{
              name: 'v1-marketing-bill-recharge-delete-bill-recharge',
              flag: 'v1/marketing/bill-recharge/delete-bill-recharge',
            }"
            >删除</a
          >
        </span>
      </template>
    </Table>

    <Page
      :total="total"
      class="ivu-mt-16"
      :current.sync="params.page"
      :page-size="params.pageSize"
      @on-change="changePage"
      show-total
      show-elevator
      show-sizer
      @on-page-size-change="changePageSize"
    />

    <Modal
      v-model="showForm"
      :title="isEdit ? '编辑' : '新增'"
      :draggable="true"
      :mask-closable="false"
      @on-cancel="handleCancel"
      footer-hide
    >
      <Form
        :model="formItem"
        :label-width="80"
        ref="formItem"
        :rules="createRules"
      >
        <FormItem label="项目" prop="project_id">
          <Select v-model="formItem.project_id" placeholder="请选择项目">
            <Option
              :value="+item.value"
              v-for="item in projectList"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="渠道" prop="subdivided_channels_id">
          <Select
            filterable
            v-model="formItem.subdivided_channels_id"
            placeholder="请选择渠道"
          >
            <OptionGroup
              v-for="item in channelList"
              :key="item.value"
              :label="item.label"
            >
              <Option
                :value="+el.value"
                v-for="el in item.children"
                :key="el.value"
                >{{ el.label }}</Option
              >
            </OptionGroup>
          </Select>
        </FormItem>
        <FormItem label="充值金额" prop="real_money">
          <Input
            type="number"
            v-model="formItem.real_money"
            placeholder="请输入充值金额"
          />
        </FormItem>
        <FormItem label="充值日期" prop="pay_date">
          <DatePicker
            type="date"
            v-model="formItem.pay_date"
            :clearable="false"
            :transfer="true"
            placeholder="充值日期"
            style="width: 100%"
          />
        </FormItem>
      </Form>

      <div class="modalFoot">
        <Button @click="handleCancel()">取消</Button>
        <Button
          class="ivu-ml-16"
          :loading="btnLoading"
          type="primary"
          @click="handleSave()"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  billList,
  billCreate,
  billDel,
  synDingtalk,
  synDingtalkStatus,
} from "@/api/hqapi";
export default {
  name: "statementaccount",
  data() {
    return {
      synLoading: false,
      loading: false,
      btnLoading: false,
      isEdit: false,
      showForm: false,
      projectList: [],
      channelList: [],
      params: {
        date: [
          this.$Date().startOf("month").format("YYYY-MM-DD"),
          this.$Date().format("YYYY-MM-DD"),
        ],
        project_id: null,
        channel_id: [],
        page: 1,
        pageSize: 10,
      },
      total: 0,
      columns: [
        {
          title: "项目",
          key: "project_name",
        },
        {
          title: "渠道",
          slot: "channel_name",
          minWidth: 120,
        },
        {
          title: "金额",
          key: "real_money",
        },
        {
          title: "类型",
          slot: "type_name",
        },
        {
          title: "充值日期",
          key: "pay_date",
        },
        {
          title: "创建日期",
          key: "created_at_str",
        },
        {
          title: "人员",
          key: "apply_member_name",
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 110,
        },
      ],
      data: [],
      formItem: {
        project_id: null,
        channel_id: null,
        subdivided_channels_id: null,
        real_money: null,
        pay_date: "",
      },
      createRules: {
        project_id: [
          {
            required: true,
            type: "number",
            message: "请选择项目",
            trigger: "change",
          },
        ],
        subdivided_channels_id: [
          {
            required: true,
            type: "number",
            message: "请选择渠道",
            trigger: "change",
          },
        ],
        real_money: [
          {
            required: true,
            message: "请输入充值金额",
            trigger: "blur",
          },
        ],
        pay_date: [
          {
            required: true,
            type: "date",
            message: "请选择充值日期",
            trigger: "change",
          },
        ],
      },
    };
  },

  methods: {
    initData() {
      this.formItem = {
        project_id: "",
        channel_id: "",
        subdivided_channels_id: "",
        real_money: null,
        pay_date: "",
      };
      this.$refs.formItem.resetFields();
    },
    handleSummary({ columns, data }) {
      const checkArr = "real_money";
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 0) {
          sums[key] = {
            key,
            value: "合计",
          };
          return;
        } else if (checkArr == key) {
          const values = data.map((item) => Number(item[key]));
          if (!values.every((value) => isNaN(value))) {
            const v = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return Number(prev) + Number(curr);
              } else {
                return prev;
              }
            }, 0);
            sums[key] = {
              key,
              value: v.toFixed(2),
            };
          } else {
            sums[key] = {
              key,
              value: "",
            };
          }
        } else {
          sums[key] = {
            key,
            value: "",
          };
          return;
        }
      });

      return sums;
    },
    getData(type = false) {
      let params = {
        project_id: this.params.project_id,
        channel_id: this.params.channel_id,
        pay_date_start: this.params.date[0]
          ? this.$Date(this.params.date[0]).format("YYYY-MM-DD")
          : "",
        pay_date_end: this.params.date[1]
          ? this.$Date(this.params.date[1]).format("YYYY-MM-DD")
          : "",
        page: this.params.page,
        pageSize: this.params.pageSize,
      };
      this.loading = true;
      billList(params)
        .then((res) => {
          if (!res.syn_dingtalk_status) {
            if (!this.synLoading) {
              this.synLoading = true;
              this.checkStatus();
            }
          }
          if (type) {
            this.projectList = res.condition.project_arr;
            this.channelList = res.condition.channel_arr;
          }

          this.data = res.list;
          this.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    askData(e) {
      this.params.page = 1;
      this.getData();
    },
    changePage(e) {
      this.params.page = e;
      this.getData();
    },
    changePageSize(e) {
      this.params.pageSize = e;
      this.getData();
    },
    handleAdd() {
      this.isEdit = false;
      this.initData();
      this.showForm = true;
    },
    handleEdit(row) {
      this.isEdit = true;
      this.initData();
      this.formItem = {
        id: row.id,
        project_id: +row.project_id,
        channel_id: +row.channel_id,
        subdivided_channels_id: +row.subdivided_channels_id,
        real_money: +row.real_money,
        pay_date: row.pay_date,
      };
      this.showForm = true;
    },
    findFirstChannel(id) {
      let res = "";
      this.channelList.forEach((item) => {
        if (item.children && item.children.length > 0) {
          item.children.forEach((el) => {
            if (id == el.value) {
              return (res = el.pid);
            }
          });
        }
      });
      return res;
    },
    handleSave() {
      this.$refs.formItem.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let params = {
            project_id: this.formItem.project_id,
            channel_id: this.findFirstChannel(
              this.formItem.subdivided_channels_id
            ),
            subdivided_channels_id: this.formItem.subdivided_channels_id,
            real_money: this.formItem.real_money,
            pay_date: this.$Date(this.formItem.pay_date).format("YYYY-MM-DD"),
          };
          if (this.isEdit) {
            params.id = this.formItem.id;
          }
          billCreate(params)
            .then((res) => {
              this.btnLoading = false;
              this.$Message.success("提交成功!");
              this.showForm = false;
              this.getData();
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    handleDel(row) {
      this.$Modal.confirm({
        title: "删除确认",
        content: "删除后将不可恢复，是否确认删除",
        loading: true,
        onOk: () => {
          billDel({ id: row.id })
            .then(() => {
              this.getData();
              this.$Modal.remove();
            })
            .catch(() => {
              this.$Modal.remove();
            });
        },
      });
    },

    handleCancel() {
      this.showForm = false;
    },
    checkStatus() {
      synDingtalkStatus().then((res) => {
        if (res) {
          this.$Message.success("同步成功!");
          this.getData();
          this.synLoading = false;
        } else if (this.synLoading) {
          setTimeout(() => {
            this.checkStatus();
          }, 5 * 1000);
        }
      });
    },
    synchronous() {
      this.synLoading = true;
      synDingtalk()
        .then((res) => {
          this.checkStatus();
        })
        .catch(() => {
          this.synLoading = false;
        });
    },
  },
};
</script>
<style lang="less" scoped>
.modalFoot {
  text-align: right;
  border-top: 1px solid #ddd;
  padding-top: 16px;
  margin-top: 24px;
}
.del {
  color: red;
}
.nochannel {
  color: red;
}
</style>
